package sdk.webview.fmc.com.fmcsdk.service;


import static sdk.webview.fmc.com.fmcsdk.activity.H5Activity.NOTIFY_INSPECION_STATUS;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import sdk.webview.fmc.com.fmcsdk.base.BaseData;
import sdk.webview.fmc.com.fmcsdk.base.BindEventBus;
import sdk.webview.fmc.com.fmcsdk.base.UserApi;
import sdk.webview.fmc.com.fmcsdk.bean.CaUploadImage;
import sdk.webview.fmc.com.fmcsdk.bean.GETREPORTBean;
import sdk.webview.fmc.com.fmcsdk.bean.StartPauseBean;
import sdk.webview.fmc.com.fmcsdk.bean.SubMitPointBean;
import sdk.webview.fmc.com.fmcsdk.bean.UnCheckPointBean;
import sdk.webview.fmc.com.fmcsdk.bean.UploadImage;
import sdk.webview.fmc.com.fmcsdk.check.CacheHelper;
import sdk.webview.fmc.com.fmcsdk.check.bean.GetDetailsBean;
import sdk.webview.fmc.com.fmcsdk.db.DatabaseManager;
import sdk.webview.fmc.com.fmcsdk.imagepicker.utils.Utils;
import sdk.webview.fmc.com.fmcsdk.upload.ImageUploadBean;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.DateUtil;
import sdk.webview.fmc.com.fmcsdk.util.FastClickHelper;
import sdk.webview.fmc.com.fmcsdk.util.FileUtil;
import sdk.webview.fmc.com.fmcsdk.util.GsonUtil;
import sdk.webview.fmc.com.fmcsdk.util.HandleJsEvent;
import sdk.webview.fmc.com.fmcsdk.util.HttpsUtils;
import sdk.webview.fmc.com.fmcsdk.util.ImageUtils;
import sdk.webview.fmc.com.fmcsdk.util.KLog;
import sdk.webview.fmc.com.fmcsdk.util.NetworkUtils;
import sdk.webview.fmc.com.fmcsdk.util.UpLoadEvent;
import sdk.webview.fmc.com.fmcsdk.util.Url;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ApiFactory;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.ResponseSubscriber;

@BindEventBus
public class NetworkListenerService extends Service {

    private BroadcastReceiver networkReceiver;
    private DatabaseManager databaseManager;
    private String baseUrl;
    private SharedPreferences defaultSharedPreferences;

    private int timeTime;

    private int uploadImgNum;//上传失败


    private long startTime = System.currentTimeMillis();


    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(NetworkListenerService.this);
        baseUrl = defaultSharedPreferences.getString(Constant.BASE_ADDRESS_URL, "");
        databaseManager = new DatabaseManager(NetworkListenerService.this);
        registerNetworkReceiver();
    }


    private Handler backgroundHandler;

    private void registerNetworkReceiver() {
        networkReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                isNetOne = false;
                HandlerThread handlerThread = new HandlerThread("BackgroundThread");
                handlerThread.start();
                Looper looper = handlerThread.getLooper();
                if (backgroundHandler == null) {
                    backgroundHandler = new Handler(looper);
                }
                backgroundHandler.postDelayed(thread, 1000);
                timeTime = 0;
            }
        };
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkReceiver, filter);
    }

    public void checkNetworkAndUpload() {
        if (!NetworkUtils.isAvailable(getApplicationContext())) {
            return;
        }
        try {
            startTime = System.currentTimeMillis();
            isError = false;
            isFinish = false;
            // 检查图片是否需要上传
            isNeedUploadPic();
            initGetReportStatus();
            //检查巡检点是否需要上传
            isNeedUploadCheckPoint();
            //检查巡检单状态是否需要上传
            isNeedUploadCheckState();//开始暂停
            startImg();
        } catch (Exception e) {

        } finally {
            requestFinish();
        }


    }


    private void requestFinish() {
        boolean isHave = false;
        List<StartPauseBean> inspectStateList = CacheHelper.getInstance().getStartPause();
        List<CaUploadImage> pointImage = CacheHelper.getInstance().getUploadImage();
        for (CaUploadImage bean : pointImage) {
            for (int i = 0; i < bean.getImageList().size(); i++) {
                isHave = true;
            }
        }
        KLog.e(isHave);
        KLog.e(GsonUtil.BeanToJson(pointImage));
        List<GETREPORTBean> list1 = CacheHelper.getInstance().getOnLineNoGET_REPORT_STATUS();
        List<SubMitPointBean> subMitListBean = CacheHelper.getInstance().getSubmitPoint();
        if (Utils.isEmpty(inspectStateList) & !isHave & Utils.isEmpty(list1) & Utils.isEmpty(subMitListBean)) {
            List<StartPauseBean> list = CacheHelper.getInstance().getFinish();
            KLog.e(list.size());
            for (int i = 0; i < list.size(); i++) {
                StartPauseBean bean = list.get(i);
                if (isNet == 0) {
                    break;
                }
                getCheckComplete(bean.getId(), bean.getJson(), bean.getTaskId(), bean.getRemark(), bean.getTime() + "", bean.getData(), bean.gettId(), i);
            }
        }
    }

    private void isNeedUploadCheckPoint() {
        List<SubMitPointBean> subMitListBean = CacheHelper.getInstance().getSubmitPoint();
        KLog.e(subMitListBean.size());
        for (int i = 0; i < subMitListBean.size(); i++) {
            SubMitPointBean bean = subMitListBean.get(i);
            if (isNet == 0) {
                break;
            }
            uploadCheckPoint(bean.getProjId(), bean.getJson(), bean.getPointId(), i == subMitListBean.size() - 1, i);
        }

        List<StartPauseBean> startPauseBeans = CacheHelper.getInstance().getJumpPoint();
        for (int i = 0; i < startPauseBeans.size(); i++) {
            StartPauseBean bean = startPauseBeans.get(i);
            int finalI = i;
           uploadCheckPointJump(bean.getPorId(), bean.getJson(), finalI);
        }

    }


    private void isNeedUploadCheckState() {
        List<StartPauseBean> inspectStateList = CacheHelper.getInstance().getStartPause();
        KLog.e(inspectStateList.size());
        if (!inspectStateList.isEmpty()) {
            KLog.e("success" + GsonUtil.BeanToJson((inspectStateList)));
            String json = inspectStateList.get(0).getJson();
            String id = inspectStateList.get(0).getId();
            uploadCheckState(id, GsonUtil.GsonToMaps(json), 0, inspectStateList);
        }


    }


    private void uploadCheckState(String projid, Map<String, Object> map, int position, List<StartPauseBean> startPauseBeans) {
        KLog.e("success");
       // map.put("operateTime", System.currentTimeMillis() + "");
        //  map.put("actStartDate", System.currentTimeMillis()+"");
        KLog.e("huohuohuohuo" + GsonUtil.BeanToJson(map));
        ApiFactory.getFactory().create(UserApi.class).apiGetSpStatus(baseUrl + Url.GET_SPSTATUS, UserHelper.getToken(), map.get("projId") + "", map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseData>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        isError = true;
                        KLog.e("huohuohuohuo+success");
                    }

                    @Override
                    public void onNext(BaseData result) {
                        KLog.e("huohuohuohuosuccess");
                        String status = (String) map.get("orderOperate");
                        String params = projid + "," + map.get("taskId") + "," + (TextUtils.equals(status, "START") ? "1" : "0");
                        EventBus.getDefault().post(new HandleJsEvent(NOTIFY_INSPECION_STATUS, params));
                        CacheHelper.getInstance().removeStartPause(position);
                        startPauseBeans.remove(position);
                        CacheHelper.getInstance().saveUpImageList(map.get("id").toString(), map.get("des").toString(), 0, -1);
                        KLog.e(position);
                        EventBus.getDefault().post(new UploadEventLoad());
                        if (!Utils.isEmpty(startPauseBeans)) {
                            String json = startPauseBeans.get(0).getJson();
                            String id = startPauseBeans.get(0).getId();
                            uploadCheckState(id, GsonUtil.GsonToMaps(json), position, startPauseBeans);
                        }
                        if(startPauseBeans.size()<=0){
                            requestFinish();
                        }
                    }
                });
    }

    private boolean isFinish;

    private void uploadCheckPoint(String projid, String json, String id, boolean isLAst, int position) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("raw"), json);
        ApiFactory.getFactory().create(UserApi.class).updateInspectionPoint(baseUrl + Url.POST_UPDATE_POINT, UserHelper.getToken(), projid, requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseData>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        isNeedUploadCheckPoint();
                    }

                    @Override
                    public void onNext(BaseData result) {
                        CacheHelper.getInstance().removeSubmitPoint(id, projid, position);
                        EventBus.getDefault().post(new UploadEventLoad());
                        isNeedUploadCheckPoint();
                        requestFinish();
                    }
                });
    }

    private void uploadCheckPointJump(String projid, String json, int position) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("raw"), json);
        ApiFactory.getFactory().create(UserApi.class).updateInspectionPoint(baseUrl + Url.POST_UPDATE_POINT, UserHelper.getToken(), projid, requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseData>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        isError = true;
                    }

                    @Override
                    public void onNext(BaseData result) {
                        // CacheHelper.getInstance().deletePoint(id + "");
                        CacheHelper.getInstance().removeJumpPoint(position);
                        EventBus.getDefault().post(new UploadEventLoad());
                        requestFinish();
                    }
                });
    }

    private void isNeedUploadPic() {
        List<CaUploadImage> pointImage = CacheHelper.getInstance().getUploadImage();
        KLog.e(pointImage.size());
        KLog.e("开始上传" + pointImage.size());
        for (CaUploadImage bean : pointImage) {
            for (int i = 0; i < bean.getImageList().size(); i++) {
                ImageUploadBean item = bean.getImageList().get(i);
                boolean isLast = i == bean.getImageList().size() - 1;
                KLog.e("111" + isNet);
                // 提交任务到线程池
                if (isNet == 0) {
                    break;
                }
                KLog.e("222");
                int finalI = i;
                // executor.submit(() -> {
                KLog.e("开始上传" + finalI);
                uploadPic(item.getPath(), item.getIds(), item, isLast);
                // });
            }
        }
        // 关闭线程池
        // executor.shutdown();

    }

    boolean isError;

    private void uploadPic(String url, String ids, ImageUploadBean bean, boolean isLAst) {
        KLog.e("开始上传");
        File files = new File(url);
        if (!files.exists()) {
            files = new File(url);
            if (!files.exists()) {
                return;
            }
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), files);
        RequestBody typeBody = RequestBody.create(MediaType.parse("multipart/form-data"), ids.split("\\.")[0]);//,System.currentTimeMillis()+""
        RequestBody timeBody = RequestBody.create(MediaType.parse("multipart/form-data"), System.currentTimeMillis() + "");//,+""
        ApiFactory.getFactory().create(UserApi.class).uploadImgForClient(baseUrl + Url.UPLOAD_IMG, Url.XMLHTTPREQUEST, UserHelper.getToken(), requestBody, typeBody, timeBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<UploadImage>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        //Constant.allNum = 1;
                        KLog.e("uploaderror");
                        isError = true;
                    }

                    @Override
                    public void onNext(UploadImage baseData) {
                        KLog.e("开始ok");
                        if (null != baseData) {
                            List<UploadImage.RecordBean> record = baseData.getRecord();
                            if (null != record && !record.isEmpty()) {
                                UploadImage.RecordBean recordBean = record.get(0);
                                if (null != recordBean) {
                                    EventBus.getDefault().post(new UploadEventLoad());
                                    String url = recordBean.getUrl();
                                    String markersUrl = recordBean.getThumburl();
                                    KLog.e(url + "-----" + markersUrl);
                                    String picId = recordBean.getId();
                                    updateInspectionPointWorkRequest(picId, url, url, bean.getPointCheckId(), bean.getPathUri(), bean.getDes(), bean);
                                }
                            }
                        }
                    }
                });
    }


    @Override
    public void onDestroy() {
        unregisterReceiver(networkReceiver);
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    private boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private static int isNet = 1;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(NetworkListEvent event) {
        if (event == null) return;
        isNet = event.getNetWork();
        KLog.e("isNet---" + isNet);
        checkNetworkAndUpload();
    }


    public void updateInspectionPointWorkRequest(String picId, String url, String shrinkUrl, String ownerId, String locationUrl, String description, ImageUploadBean bean) {
        String ownerObject = "insp_order_chklist";
        String ownerType = "chklist";
        String storePath = "/filestorage/" + DateUtil.getCurrentDate("yyyyMMdd") + "/" + picId + ".jpg";
        String thumbImagePath = "/filestorage/" + DateUtil.getCurrentDate("yyyyMMdd") + "/thumb_" + picId + ".jpg";
        String offlineDate = DateUtil.getCurrentDate("yyyy/MM/dd+HH:mm:ss");
        Log.e("霍东升检查参数：", "url==>" + baseUrl + Url.UPLOAD_FILES_SERVICE + "\n" +
                "X-Requested-With===>" + Url.XMLHTTPREQUEST + "\n" +
                "accessToken===>" + UserHelper.getToken() + "\n" +
                "accessToken ===>" + UserHelper.getToken() + "\n" +
                "ids ===>" + picId + "\n" +
                "ownerId ===>" + ownerId + "\n" +
                "ownerObject ===>" + ownerObject + "\n" +
                "ownerType ===>" + ownerType + "\n" +
                "storePath ===>" + storePath + "\n" +
                "suffix ===>" + "jpg\n" +
                "thumbImagePath ===>" + thumbImagePath + "\n" +
                "type ===>" + "IMAGE\n" +
                "offlineDate ===>" + offlineDate + "\n" +
                "description ===>" + description);

        ApiFactory.getFactory().create(UserApi.class).updateInspectionPointWorkRequest(baseUrl + Url.UPLOAD_FILES_SERVICE, Url.XMLHTTPREQUEST,
                        UserHelper.getToken(), UserHelper.getToken(), picId, ownerId, ownerObject, ownerType, storePath, "jpg", thumbImagePath, "IMAGE", offlineDate, description)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResponseSubscriber<BaseData>() {
                    @Override
                    public void success(BaseData baseData) {
                        KLog.e("2222", "success" + url);
                        GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO pictureUrlsDTO = new GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO();
                        pictureUrlsDTO.setUrl(url);
                        pictureUrlsDTO.setThumburl(url);
                        pictureUrlsDTO.setId(picId);
                        CacheHelper.getInstance().setImageSuccess(bean.getPath(), bean.getPointId());
                        FileUtil.deleteOneFile(ImageUtils.getH5ImagePath(bean.getIds(), NetworkListenerService.this));
                        EventBus.getDefault().post(new UpLoadEvent());
                        EventBus.getDefault().post(new UploadEventLoad());
                        requestFinish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        KLog.e("开始error");
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {
                        updateInspectionPointWorkRequest(picId, url, shrinkUrl, ownerId, locationUrl, description, bean);
                    }
                });
    }

    boolean isNetOne;


    private Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                final String address = sharedPrefs.getString(Constant.BASE_ADDRESS_URL, "");
                List<String> list = HttpsUtils.getIps(address);
                String ip = "www.baidu.com";
                if (!HttpsUtils.isEmpty(list)) {
                    ip = list.get(0);
                    //Log.e("ip11111", ip);
                }
                Process ipProcess = null;// -c 次数 -w 超时
                ipProcess = Runtime.getRuntime().exec("ping -c 1 " + ip);
                //exitValue==0网络可用，否则网络不可用
                int exitValue = ipProcess.waitFor();
                ipProcess.destroy();
                Message message = new Message();
                message.arg1 = exitValue;
                // handler.sendMessageDelayed(message, 2000);
                if (exitValue == 0) {
                    isNet = 1;
                    if (!isNetOne) {
                        checkNetworkAndUpload();
                        isNetOne = true;
                    }
                } else {
                    isNet = 0;
                }
                if (System.currentTimeMillis() - startTime >= 30000) {
                    if (exitValue == 0) {
                        //  if (isError || isFinish) {
                        checkNetworkAndUpload();
                        //  }
                    }
                }
                backgroundHandler.postDelayed(thread, 3000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    public void initGetReportStatus() {
        List<GETREPORTBean> list = CacheHelper.getInstance().getOnLineNoGET_REPORT_STATUS();
        KLog.e(list.size());
        for (int i = 0; i < list.size(); i++) {
            GETREPORTBean bean = list.get(i);
            if (isNet == 0) {
                break;
            }
            getReportStatus(bean);
        }


    }

    public void getReportStatus(GETREPORTBean bean) {
        String time = System.currentTimeMillis() + "";
        ApiFactory.getFactory().create(UserApi.class).apiReportStatus(baseUrl + Url.GET_REPORT_STATUS, UserHelper.getToken(), bean.getAssetId(), bean.getType(), time, time, bean.getProjId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResponseSubscriber<BaseData>() {
                    @Override
                    public void success(BaseData baseData) {
                        KLog.e(GsonUtil.BeanToJson(bean));
                        CacheHelper.getInstance().removeGetReportStatus(bean);
                        EventBus.getDefault().post(new UploadEventLoad());
                        requestFinish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        isError = true;
                        timeTime = timeTime + 1;
                        if (timeTime > 10) return;
                        initGetReportStatus();
                    }

                    @Override
                    public void onRequestAgain() {

                    }
                });
    }


    private void isNeedFinish(String id, String proId, String tId, String taskId) {
        ApiFactory.getFactory().create(UserApi.class).getUnCheckPoint(baseUrl + Url.GET_UNCHECK_POINT, UserHelper.getToken(), id, proId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResponseSubscriber<UnCheckPointBean>() {
                    @Override
                    public void success(UnCheckPointBean baseData) {
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {
                    }


                });
    }


    public void getCheckComplete(String projid, String id, String taskId, String compRemark, String operateTime, String pushStaffIds, String tid, int position) {
        ApiFactory.getFactory().create(UserApi.class).getCheckComplete(baseUrl + Url.GET_CHECK_COMPLETE, UserHelper.getToken(), projid, id, taskId, compRemark, operateTime+"", "1", pushStaffIds)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResponseSubscriber<BaseData>() {
                    @Override
                    public void success(BaseData baseData) {
                        CacheHelper.getInstance().removeFinish(position);
                        KLog.e("success");
                        String params = tid + "," + taskId + "," + "2";
                        EventBus.getDefault().post(new HandleJsEvent(NOTIFY_INSPECION_STATUS, params));
                        EventBus.getDefault().post(new UploadEventLoad());
                    }

                    @Override
                    public void onError(Throwable e) {
                        isError = true;
                    }

                    @Override
                    public void onRequestAgain() {
                    }


                });
    }
    public void startImg() {
        if (!FastClickHelper.isFastClick()) return;
        try {
            //没有设置仅wifi上传
                startQueryFile(true, true);
        } catch (Exception e) {
        }
    }
    private void startQueryFile(boolean iswifiupim, boolean iswifiupvi) {
        UploadFileManager.getInstance().startQueryFile(this, iswifiupim, iswifiupvi, null);
    }

}
